
from openai import OpenAI
import logging
from typing import List, Dict, Any

logger = logging.getLogger(__name__)

class TextGenerationService:

    @staticmethod
    def generate_text(prompt: str, number: int) -> Dict[str, Any]:
        """
        按提示词与数量生成文本

        Args:
            prompt (str): 文本生成提示词
            number (int): 需要生成的数量

        Returns:
            Dict[str, Any]: 生成的文本与状态
        """
        try:
            # TODO: API放到环境变量
            client = OpenAI(
                api_key="sk-d0f02fe402c14d8da341b0d19a4f0032", #TODO 填入API
                base_url="https://api.deepseek.com"
            )
            
            # Generate texts using DeepSeek API
            generated_texts = []
            for i in range(number):
                print("正在进行第 " , i+1," / " , number, " 次请求")
                response = client.chat.completions.create(
                    model="deepseek-chat",
                    messages=[
                        {"role": "system", "content": "假设你是一个真正的人在进行评论,面对给出的情景，你可以任选一种角度进行评论，评论要像真人一样自然，但无论是长评论还是短评论，总字数一定要在100子以内"},
                        {"role": "user", "content": prompt}
                    ],
                    temperature=1.5,  # 高随机性
                    top_p=0.9,  # 高多样性
                    max_tokens=500,  # 生成长文本
                    frequency_penalty=0.7,  # 减少重复
                    presence_penalty=0.7,  # 增加新内容
                    stream=False
                )
                generated_text = response.choices[0].message.content
                generated_texts.append(generated_text)
                
                # TODO: 存储到数据库
                print(generated_text)
                print("#################")
                
            return {
                "status": "success",
                "generated_texts": generated_texts
            }
            
        except Exception as e:
            logger.exception("Text generation failed")
            return {
                "status": "error",
                "message": f"Text generation failed: {str(e)}"
            } 